package com.daisuxia.web.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.daisuxia.back.utils.RequestUtils;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.dao.IIndexDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.Orders;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.service.BackConfigParamsService;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.OrdersService;
import com.daisuxia.web.service.UserBankService;
import com.daisuxia.web.service.UserService;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.encrypt.AESUtil;
import com.daisuxia.web.util.encrypt.MD5coding;

import redis.clients.jedis.JedisCluster;

/**
 * 用户借款记录
 * 
 * @author 2016年12月9日 16:51:09
 * @param
 */
@Controller
@RequestMapping("credit-loan/")
public class UserloanController extends BaseController {
	Logger logger = Logger.getLogger(UserloanController.class);
	@Autowired
	private UserBankService userBankService;
	@Autowired
	private BackConfigParamsService backConfigParamsService;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private UserService userService;
	@Autowired
	private IIndexDao indexDao;
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	OrdersService ordersService;
	
	/**
	 * H5 借款说明
	 */
	@RequestMapping("description")
	public String borrowDescription(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "borrow/borrowDescription";
	}

	public ServiceResult allowBorrow(HashMap<String, String> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常");
		String key = "xjx_borrow_confirm_loan"; // redis key
		Integer userId = Integer.valueOf(params.get("userId"));
		try {
			User user = userService.searchByUserid(userId);
			jedisCluster.setex(key, 60, userId + "");
			if (!"2".equals(user.getNewFlag())) {
				serviceResult.setMsg("您当前为新用户，信用正在审核中，请您耐心等待");
			} else {
				if (StringUtils.isBlank(params.get("money")) || StringUtils.isBlank(params.get("period"))) {
					serviceResult.setMsg("参数错误");
				} else {
					String currperiodIsopen = "0";// 默认关
					String currperiod = params.get("period");// 当前借款期限
					Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
					String periodTypes = keys.get("period_type_isopen");
					try {

						String periodTypesArr[] = periodTypes.split(";"); 
						for (String p : periodTypesArr) {
							String period[] = p.split(":");
							if (currperiod.equals(period[0])) {
								currperiodIsopen = period[1];
								break;
							}
						}
					} catch (Exception e) {
						logger.error("judge periodsTypeIsOpen error", e);
					}

					if (!currperiodIsopen.equals("1")) {
						serviceResult.setMsg("暂不受理" + currperiod + "天借款服务");    
					} else {
						if (!"1".equals(user.getRealnameStatus())) {
							serviceResult.setMsg("请先实名认证");
						} else {
							if ("2".equals(user.getStatus())) {
								serviceResult.setMsg("您为黑名单用户，暂不能借款");
							} else {
								if (StringUtils.isBlank(user.getFirstContactPhone()) || StringUtils.isBlank(user.getSecondContactPhone())) {
									serviceResult.setMsg("请完善紧急联系人信息");
								} else {
									if ("1".equals(user.getZmStatus())) {
										serviceResult.setMsg("芝麻信用未认证");
									} else {
										if ("1".equals(user.getJxlStatus())) {
											serviceResult.setMsg("手机运营商未认证");
										} else {
											Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(user.getId()));
											if (1 == checkResult) {
												serviceResult.setMsg("您有借款申请正在审核或未还款完成，暂不能借款。");
											} else {
												Integer money = Integer.parseInt(params.get("money"));
												if (money < 10) {
													serviceResult.setMsg("您的借款金额不能低于10元。");
												} else {
													int minAmount = Integer.parseInt(user.getAmountMin()) / 100;
													if (minAmount <= 0) {
														serviceResult.setMsg("您的最低借款额度为0元，暂不能借款。");
													} else if (money < minAmount) {
														serviceResult.setMsg("您的最低借款额度为" + minAmount + "元。");
													} else {
														int maxAmount = Integer.parseInt(user.getAmountMax()) / 100;
														if (maxAmount <= 0) {
															serviceResult.setMsg("您的最高借款额度为0元，暂不能借款。");
														} else if (money > maxAmount) {
															serviceResult.setMsg("您的最高借款额度为" + maxAmount + "元。");
														} else {
															int amountAvailable = Integer.parseInt(user.getAmountAvailable()) / 100;
															if (amountAvailable <= 0) {
																serviceResult.setMsg("您的剩余可借额度为0元，暂不能借款。");
															} else if (money > amountAvailable) {
																serviceResult.setMsg("您的剩余可借额度为" + amountAvailable + "元");
															} else {
																// 系统最大额度
																Integer sysAmountMax = Integer.parseInt(keys.get("max_amount_sys")) / 100;
																if (money > sysAmountMax) {
																	serviceResult.setMsg("您目前最高可借款额度不能超过" + sysAmountMax + "元。");
																} else {
																	Map<String, String> interval = borrowOrderService
																			.findAuditFailureOrderByUserId(user.getId());
																	if ("-1".equals(interval.get("code"))) {
																		serviceResult.setExt(interval.get("canLoan"));
																		serviceResult.setMsg(interval.get("msg"));
																	} else {
																		serviceResult = new ServiceResult(ServiceResult.SUCCESS, "可以借款");
																	}
																}
															}
														}
													}
												}
											}
										}
									}

								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("allowBorrow error ", e);
		} finally {
			return serviceResult;
		}
	}

	/**
	 * 
	 * 融360接口验证用户信息
	 * @param params
	 * @return
	 */
	@SuppressWarnings("finally")
	public ServiceResult allowBorrowfor(HashMap<String, String> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常");
		String key = "xjx_borrow_confirm_loan"; // redis key
		Integer userId = Integer.valueOf(params.get("userId"));
		try {
			User user = userService.searchByUserid(userId);
			jedisCluster.setex(key, 60, userId + "");
			if (!"2".equals(user.getNewFlag())) {
				serviceResult.setMsg("您当前为新用户，信用正在审核中，请您耐心等待");
			} else {
				if (StringUtils.isBlank(params.get("money")) || StringUtils.isBlank(params.get("period"))) {
					serviceResult.setMsg("参数错误");
				} else {
					Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(user.getId()));
					if (1 == checkResult) {
						serviceResult.setMsg("您有借款申请正在审核或未还款完成，暂不能借款。");
					} else {
						Integer money = Integer.parseInt(params.get("money"));
						if (money < 10) {
							serviceResult.setMsg("您的借款金额不能低于10元。");
						} else {
							int minAmount = Integer.parseInt(user.getAmountMin()) / 100;
							if (minAmount <= 0) {
								serviceResult.setMsg("您的最低借款额度为0元，暂不能借款。");
							} else if (money < minAmount) {
								serviceResult.setMsg("您的最低借款额度为" + minAmount + "元。");
							} else {
								int maxAmount = Integer.parseInt(user.getAmountMax()) / 100;
								if (maxAmount <= 0) {
									serviceResult.setMsg("您的最高借款额度为0元，暂不能借款。");
								} else if (money > maxAmount) {
									serviceResult.setMsg("您的最高借款额度为" + maxAmount + "元。");
								} else {
									int amountAvailable = Integer.parseInt(user.getAmountAvailable()) / 100;
									if (amountAvailable <= 0) {
										serviceResult.setMsg("您的剩余可借额度为0元，暂不能借款。");
									} else if (money > amountAvailable) {
										serviceResult.setMsg("您的剩余可借额度为" + amountAvailable + "元");
									} else {
										// 系统最大额度
										Map<String, String> keys = SysCacheUtils.getConfigParams(BackConfigParams.SYS_FEE);
										Integer sysAmountMax = Integer.parseInt(keys.get("max_amount_sys"))/100;
										if (money > sysAmountMax) {
											serviceResult.setMsg("您目前最高可借款额度不能超过" + sysAmountMax + "元。");
										} else {
											Map<String, String> interval = borrowOrderService
													.findAuditFailureOrderByUserId(user.getId());
											if ("-1".equals(interval.get("code"))) {
												serviceResult.setExt(interval.get("canLoan"));
												serviceResult.setMsg(interval.get("msg"));
											} else {
												serviceResult = new ServiceResult(ServiceResult.SUCCESS, "可以借款");
											}
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("allowBorrow error ", e);
		} finally {
			return serviceResult;
		}
	}

	/**
	 * to 借款
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("get-confirm-loan")
	public void confirmLoan(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> json = new HashMap<String, Object>();
		String code = Status.FAILD.getName();
		String msg = "获取失败";
		String key = "xjx_borrow_apply_loan"; // redis key
		boolean isDelKey = true;
		try {
			Map<String, String> params = getParameters(request);
			User user = this.loginFrontUserByDeiceId(request);
			if (user == null || StringUtils.isBlank(user.getId())) {
				msg = "请先登录";
				return;
			}
			key = key + "_" + user.getId(); // 确定key唯一
			if (StringUtils.isNotBlank(jedisCluster.get(key))) {
				isDelKey = false;
				msg = "您的借款申请正在处理中，请稍后再试";
			} else {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("userId", user.getId());
				map.put("money", params.get("money"));
				map.put("period", params.get("period"));
				ServiceResult serviceResult = allowBorrow(map);
				if (serviceResult.isSuccessed()) {
					// 从数据库获取最新的user信息，因需要判断用户的可借额度
					user = userService.searchByUserid(Integer.parseInt(user.getId()));
					// 修改用户设备号
					if (StringUtils.isBlank(user.getEquipmentNumber()) || "H5".equals(user.getEquipmentNumber())
							|| user.getUserName().equals(user.getEquipmentNumber())) {
						User u = new User();
						String equipmentNumber = request.getParameter("deviceId");// 设备号
						if (StringUtils.isBlank(equipmentNumber)) {
							if (!StringUtils.isBlank(user.getUserName())) {
								u.setId(user.getId());
								u.setEquipmentNumber(user.getUserName());
								userService.updateByPrimaryKeyUser(u);
							}
						} else {
							u.setId(user.getId());
							u.setEquipmentNumber(equipmentNumber);
							userService.updateByPrimaryKeyUser(u);
						}
					}
					HashMap<String, Object> param = new HashMap<String, Object>();
					// 查询用户的借款入账账户信息
					param.put("userId", user.getId()); //
					param.put("type", "2"); // 借记卡
					param.put("status", "1"); // 状态成功
					List<UserCardInfo> cardInfo = userBankService.findUserCardByUserId(param);//查询有效的用户银行卡信息
					UserCardInfo info = new UserCardInfo();
					if (cardInfo != null && cardInfo.size() > 0) {
						info = cardInfo.get(0);
					}/* else {
						msg = "请先绑定银行卡";
						return;
					}*/
				
					// 借款金额
					Integer loanMoney = Integer.parseInt(params.get("money"));
					// 结算服务费
					Map<String, Integer> fee = borrowOrderService.calculateApr(loanMoney * 100, Integer.parseInt(params.get("period")));
					double apr_fee = fee.get("loanApr") / 100d;
					json.put("counter_fee", String.valueOf(apr_fee));
					json.put("true_money", String.valueOf(loanMoney - apr_fee));
					json.put("period", params.get("period"));
					json.put("money", params.get("money"));
					json.put("tips", "您将在" + params.get("period") + "天后还款" + params.get("money") + "元");
					json.put("bank_name", info.getBankName() == null ? "" : info.getBankName());
					json.put("card_no", info.getCard_no() == null ? "" : info.getCard_no());
					if (info.getCard_no() != null) {
						//截取银行卡号后4位
						json.put("card_no_lastFour", info.getCard_no().substring(info.getCard_no().length()-4, info.getCard_no().length()));
					}
					json.put("protocol_msg", "");
					//借款咨询服务协议
					json.put("protocol_url",
							request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()
									+ "/credit-loan/agreement");
					//扣款协议
//					json.put("withholding_url",
//							request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()
//									+ "/agreement/withholdAuthorization");
					//平台服务协议
					json.put("platformservice_url",
							request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()
									+ "/agreement/platformServiceNew");
					//绑定银行卡H5
					json.put("firstUserBank_url", request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()
									+"/lianlianBindCard/credit-card/firstUserBank");
					json.put("real_pay_pwd_status", StringUtils.isBlank(user.getPayPassword()) ? "0" : "1"); // 支付密码状态；1：已设置支付密码；0：未设置支付密码
					json.put("verify_loan_pass", "1"); // 是否通过认证：1：认证全部通过；0：认证不通过
					code = Status.SUCCESS.getName();
					msg = Status.SUCCESS.getValue();
				} else {
					msg = serviceResult.getMsg();
				}
			}
		} catch (Exception e) {
			logger.error("credit-loan_get-confirm-loan======", e);
			e.printStackTrace();
			code = Status.ERROR.getName();
			msg = Status.ERROR.getValue();
		} finally {
			if (isDelKey) {
				try {
					jedisCluster.del(key);
				} catch (Exception e) {
					try {
						jedisCluster.expire(key, 0);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
			result.put("code", code);
			result.put("message", msg);
			data.put("item", json);
			result.put("data", data);
			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(result));
		}
	}

	/**
	 * 申请借款
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("apply-loan")
	public void applyLoan(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> item = new HashMap<String, Object>();
		String key = "xjx_borrow_apply_loan"; // redis key
		String code = Status.FAILD.getName();
		String msg = "申请失败";
		boolean isDelKey = true;
		try {
			boolean isTg = false;
			Map<String, String> params = getParameters(request);
			User user = this.loginFrontUserByDeiceId(request);
			if (user == null || StringUtils.isBlank(user.getId())) {
				String ip = RequestUtils.getIpAddr(request);
				Map<String, String> map3 = SysCacheUtils.getConfigMap(BackConfigParams.TG_SERVER);
				String value = map3.get("TG_SERVER_IP");
				if (StringUtils.isNotBlank(value)) {
					String[] ips = value.split(",");
					List<String> list = Arrays.asList(ips);
					if (list.contains(ip)) {
						isTg = true;
						user = userService.searchByUserid(Integer.valueOf(AESUtil.decrypt(params.get("userId"), map3.get("TG_SERVER_KEY"))));
					}
				}
			}
			if (user == null) {
				if (isTg) {
					msg = "用户不存在";
				} else {
					msg = "请先登录";
				}
				return;
			} else if (!isTg) {
				// 从数据库获取最新的user信息，因需要判断用户的可借额度
				user = userService.searchByUserid(Integer.parseInt(user.getId()));
			}
			key = key + "_" + user.getId(); // 确定key唯一
			if (StringUtils.isNotBlank(jedisCluster.get(key))) {
				isDelKey = false;
				msg = "您的借款申请正在处理中，请稍后再试";
			} else {
				HashMap<String, String> map2 = new HashMap<String, String>();
				map2.put("userId", user.getId());
				map2.put("money", params.get("money"));
				map2.put("period", params.get("period"));
				ServiceResult serviceResult = allowBorrow(map2);
				if (serviceResult.isSuccessed()) {
					AESUtil aesEncrypt = new AESUtil();
					String checkPassWord = MD5coding.MD5(aesEncrypt.encrypt(params.get("pay_password"), ""));// 加密
					if (!isTg && !user.getPayPassword().equals(checkPassWord)) {
						msg = "支付密码错误";
						return;
					}

					Map<String, Object> map = borrowOrderService.saveLoan(params, user);
					code = map.get("code").toString();
					msg = map.get("msg").toString();
					item.put("order_id", map.get("orderId"));
					// 申请借款成功-更新info_user_info borrow_status 状态为可见
					HashMap<String, Object> borrowMap = new HashMap<String, Object>();
					borrowMap.put("USER_ID", user.getId());
					borrowMap.put("BORROW_STATUS", "1");
					// System.out.println("borrowMap="+borrowMap+"  申请借款，需要显示进度");
					indexDao.updateInfoUserInfoBorrowStatus(borrowMap);
					jedisCluster.del(key);
				} else {
					msg = serviceResult.getMsg();
				}
			}

		} catch (Exception e) {
			logger.error("credit-loan_get-apply-loan======", e);
			e.printStackTrace();
			code = Status.ERROR.getName();
			msg = Status.ERROR.getValue();
		} finally {
			if (isDelKey) {
				try {
					jedisCluster.del(key);
				} catch (Exception e) {
					try {
						jedisCluster.expire(key, 0);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
			result.put("code", code);
			result.put("message", msg);
			data.put("item", item);
			result.put("data", data);
			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(result));
		}
	}
	/**
	 * 申请借款360
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "apply-loan360", method = RequestMethod.POST)
	public void applyLoan360(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonString2) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> item = new HashMap<String, Object>();
		String key = "xjx_borrow_apply_loan"; // redis key
		String code = Status.FAILD.getName();
		String msg = "申请失败";
		boolean isDelKey = true;
		try {
			
			String ip = RequestUtils.getIpAddr(request);
			Map<String, String> map3 = SysCacheUtils.getConfigMap(BackConfigParams.TG_SERVER);
			String value = map3.get("TG_SERVER_IP");
			logger.info("推广申请借款内部配置："+value+"；外部地址："+ip);
			if (StringUtils.isNotBlank(value)) {
				String[] ips = value.split(",");
				List<String> list = Arrays.asList(ips);
				if (!list.contains(ip)) {
					msg = "IP地址非法";
					return;
				}
			}else{
				msg = "非法请求";
				return;
			}
			
			Map<String, Object> params = JSONUtil.parseJSON2Map(jsonString2);
			
			Map<String,String> params1 = new HashMap<String,String>();
			params1.put("userId",String.valueOf(params.get("userId")));
			params1.put("money",String.valueOf(params.get("money")));
			params1.put("pay_password",String.valueOf(params.get("pay_password")));
			params1.put("period",String.valueOf(params.get("period")));
			
			logger.info("userId="+params1.get("userId"));
			User user = userService.searchByUserid(Integer.valueOf(AESUtil.decrypt(String.valueOf(params1.get("userId")), map3.get("TG_SERVER_KEY"))));
			if (user == null) {
				msg = "用户不存在";
				return;
			} 
			key = key + "_" + user.getId(); // 确定key唯一
			if (StringUtils.isNotBlank(jedisCluster.get(key))) {
				isDelKey = false;
				msg = "您的借款申请正在处理中，请稍后再试";
			} else {
				HashMap<String, String> map2 = new HashMap<String, String>();
				map2.put("userId", user.getId());
				map2.put("money", String.valueOf(params1.get("money")));
				map2.put("period", String.valueOf(params1.get("period")));
				ServiceResult serviceResult = allowBorrowfor(map2);
				logger.info("serviceResult:"+serviceResult.getCode()+",msg:"+serviceResult.getMsg());
				if (serviceResult.isSuccessed()) {
					//String checkPassWord = params1.get("pay_password");
//					if (!user.getPayPassword().equals(checkPassWord)) {
//						msg = "支付密码错误";
//						return;
//					}

					Map<String, Object> map = borrowOrderService.saveLoan(params1, user);
					
					if(params.containsKey("orderNo")){//推广系统借点钱推送订单
						ordersService.insertJdq(new Orders(user.getId() + "", BackConfigParams.JDQ, String.valueOf(params.get("orderNo")), String.valueOf(map.get("orderId"))));
					}
					code = map.get("code").toString();
					msg = map.get("msg").toString();
					item.put("order_id", map.get("orderId"));
					// 申请借款成功-更新info_user_info borrow_status 状态为可见
					HashMap<String, Object> borrowMap = new HashMap<String, Object>();
					borrowMap.put("USER_ID", user.getId());
					borrowMap.put("BORROW_STATUS", "1");
					// System.out.println("borrowMap="+borrowMap+"  申请借款，需要显示进度");
					indexDao.updateInfoUserInfoBorrowStatus(borrowMap);
					jedisCluster.del(key);
				} else {
					msg = serviceResult.getMsg();
				}
			}

		} catch (Exception e) {
			logger.error("credit-loan_get-apply-loan======", e);
			e.printStackTrace();
			code = Status.ERROR.getName();
			msg = Status.ERROR.getValue();
		} finally {
			if (isDelKey) {
				try {
					jedisCluster.del(key);
				} catch (Exception e) {
					try {
						jedisCluster.expire(key, 0);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
			result.put("code", code);
			result.put("message", msg);
			data.put("item", item);
			result.put("data", data);
			JSONUtil.toObjectJson(response, JSONUtil.beanToJson(result));
		}
	}

}
